import { PlusOutlined } from '@ant-design/icons';
import { Select as AntdSelect, SelectProps, Button, App } from 'antd';
import React, { useState, useRef, useEffect } from 'react';

import { SvgIcon } from '@/components/icon';
import { useUserInfo } from '@/store/userStore';

import { Input } from '../input';

import styles from './SimpleEditableSelect.module.scss';

interface SimpleEditableSelectProps extends Omit<SelectProps, 'options'> {
  className?: string;
  options: { label: string; value: string }[];
  onOptionsChange?: (
    newOptions: { label: string; value: string; id?: string }[],
    type: 'add' | 'delete',
  ) => Promise<boolean>;
  allowAdd?: boolean;
  allowDelete?: boolean;
  addButtonText?: string;
  placeholder?: string;
  maxLength?: number; // 新增：最大字符串长度限制
}

export const SimpleEditableSelect: React.FC<SimpleEditableSelectProps> = ({
  className,
  options = [],
  onOptionsChange,
  allowAdd = true,
  allowDelete = true,
  addButtonText = '添加类型',
  placeholder = '请选择或添加类型',
  maxLength,
  value,
  onChange,
  ...props
}) => {
  const [isAdding, setIsAdding] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [newOptionValue, setNewOptionValue] = useState('');
  const [hoveredOption, setHoveredOption] = useState<string | null>(null);
  const [hoveredDeleteIcon, setHoveredDeleteIcon] = useState<string | null>(null);
  const inputRef = useRef<any>(null);
  const selectRef = useRef<any>(null);
  const { message } = App.useApp();

  /** 超管角色判断 * */
  // #region 超管角色判断 start
  const { role } = useUserInfo();
  const isSuperAdmin = role?.code === 'super_admin';
  // #endregion 超管角色判断 end

  useEffect(() => {
    if (isAdding && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isAdding]);

  const handleAddOption = async () => {
    setIsLoading(true);
    try {
      if (newOptionValue.trim()) {
        const newOption = {
          label: newOptionValue.trim(),
          value: newOptionValue.trim(),
        };

        // 检查是否已存在相同的值
        const exists = options.some((option) => option.value === newOption.value);
        if (!exists) {
          const newOptions = [...options, newOption];
          const res = await onOptionsChange?.(newOptions, 'add');
          if (res === true) {
            message.success('添加成功');
            setNewOptionValue('');
            setIsAdding(false);

            // 自动选中新添加的选项
            setTimeout(() => {
              onChange?.(newOption.value);
            }, 100);
          } else {
            message.error('添加失败');
          }
        } else {
          message.error('该选项已存在');
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleDeleteOption = async (valueToDelete: string) => {
    setIsLoading(true);
    try {
      const newOptions = options.filter((option) => option.value !== valueToDelete);
      const res = await onOptionsChange?.(newOptions, 'delete');
      if (res === true) {
        message.success('删除成功');
        setHoveredOption(null);
        onChange?.(null);
      } else {
        message.error('删除失败');
      }
    } catch (error) {
      console.error(error);
      // message.error('删除失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleAddOption();
    } else if (e.key === 'Escape') {
      setIsAdding(false);
      setNewOptionValue('');
    }
  };

  const optionRender = (option: any) => (
    <div
      className={`${styles.optionContainer} ${hoveredDeleteIcon === option.value ? styles.deleteHovered : ''
        }`}
      onMouseEnter={() => setHoveredOption(option.value)}
      onMouseLeave={(e) => {
        // 检查鼠标是否移动到删除图标上
        const deleteIcon = e.currentTarget.querySelector(`.${styles.deleteIcon}`);
        if (!deleteIcon || !deleteIcon.contains(e.relatedTarget as Node)) {
          setHoveredOption(null);
        }
      }}
    >
      <span className={styles.optionLabel} title={option.label}>
        {option.label}
      </span>
      {allowDelete &&
        hoveredOption === option.value &&
        option.value !== '默认应用' &&
        option?.data?.type !== 'built_in' &&
        isSuperAdmin && (
          <SvgIcon
            icon={hoveredDeleteIcon === option.value ? 'delete-icons' : 'delete-icon'}
            onClick={(e) => {
              e.stopPropagation();
              handleDeleteOption(option.value);
            }}
            onMouseEnter={() => setHoveredDeleteIcon(option.value)}
            onMouseLeave={() => {
              setHoveredDeleteIcon(null);
            }}
            className={`${styles.deleteIcon} ${hoveredDeleteIcon === option.value ? styles.visible : ''
              }`}
          />
        )}
    </div>
  );

  const dropdownRender = (menu: React.ReactNode) => (
    <div>
      {menu}
      {allowAdd && isSuperAdmin && (
        <div className={styles.addSection}>
          {isAdding ? (
            <div className={styles.addInputContainer}>
              <Input
                placeholder="请输入类型"
                value={newOptionValue}
                onChange={(e) => setNewOptionValue(e.target.value)}
                onKeyDown={handleKeyPress}
                autoFocus
                maxLength={maxLength}
                showCount={!!maxLength}
              />
              <Button
                loading={isLoading}
                type="text"
                onClick={handleAddOption}
                disabled={!newOptionValue.trim()}
              >
                保存
              </Button>
              <Button
                type="text"
                onClick={() => {
                  setIsAdding(false);
                  setNewOptionValue('');
                }}
              >
                取消
              </Button>
            </div>
          ) : (
            <Button
              type="text"
              icon={<PlusOutlined />}
              onClick={() => setIsAdding(true)}
              className={styles.addButton}
            >
              {addButtonText}
            </Button>
          )}
        </div>
      )}
    </div>
  );

  return (
    <AntdSelect
      ref={selectRef}
      className={className}
      options={options}
      placeholder={placeholder}
      dropdownRender={dropdownRender}
      optionRender={optionRender}
      value={value}
      onChange={onChange}
      popupClassName={styles.customSelectDropdown}
      {...props}
    />
  );
};
